package main

import (
	"context"
	"log"
	"net/http"

	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"

	"gitee.com/jmash/jmash/trunk/jmash-core-gateway/src/jmash"

	 servicepb "jmash.com/websocket/jmash-websocket-gateway/src/jmash/websocket"
)


func main() {
	// Create a client connection to the gRPC server we just started
	// This is where the gRPC-Gateway proxies the requests
	conn, err := grpc.NewClient("0.0.0.0:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalln("Failed to dial server:", err)
	}

	gwmux := runtime.NewServeMux()
	// Register 
	err = servicepb.RegisterWebsocketHandler(context.Background(), gwmux, conn)
	if err != nil {
		log.Fatalln("Failed to register gateway:", err)
	}
	
	log.Println("OpenApi Starting !")
	// Serve the Grpc GateWay And OpenApi,
	mux := http.NewServeMux()
	mux.Handle("/", gwmux)
	
	fs := http.FileServer(http.Dir("openapi"))
	mux.Handle("/openapi/", http.StripPrefix("/openapi", fs))
	
	log.Println("Serving gRPC-Gateway on http://0.0.0.0:8090")
	
	handler := jmash.AllowCORS(mux)
	
	err = http.ListenAndServe(":8090", handler)
	if err != nil {
		log.Fatal(err)
	}
}

